package edu.gdpu.concurrent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author mazebin
 * @date 2021年 07月17日 16:54:26
 * Fail-FastTest
 * 在多线程模式下，如果某个线程对某集合进行结构上的修改，则其他线程获取该集合的迭代器，进行迭代操作时，可能出现ConcurrentModificationException
 *  解决方法：
 *  1.加入synchronized
 *  2.将非线程安全的集合改为线程安全的集合
 */
public class FailFastTest {
    public static void main(String[] args)throws Exception {
        ArrayList<Object> objects = new ArrayList<>();
        CopyOnWriteArrayList list = new CopyOnWriteArrayList();
        objects.add(new String("a"));
        objects.add(new String("b"));
        objects.add(new String("c"));
        list.add("a");
        list.add("b");
        list.add("c");
        new Thread(()->{
            try {
                synchronized (objects) {
                    Iterator<Object> iterator = objects.iterator();
                    while (iterator.hasNext()){
                        System.out.println(iterator.next());
                    }
                }
                Thread.sleep(3000);
            } catch ( InterruptedException e ) {
                e.printStackTrace();
            }
        },"thread1").start();
        new Thread(()->{
            synchronized (objects) {
                objects.remove(2);
            }
        },"thread2").start();
        System.out.println("使用CopyOnWriteArrayList");
        new Thread(()->{
            try {

                    Iterator<Object> iterator = list.iterator();
                    while (iterator.hasNext()){
                        System.out.println(iterator.next());
                    }

                Thread.sleep(3000);
            } catch ( InterruptedException e ) {
                e.printStackTrace();
            }
        },"thread3").start();
        new Thread(()->{
            list.remove(2);

        },"thread2").start();

    }
}
